#!/usr/bin/python
# -*- coding: UTF-8 -*- 
# python 3.8.10 汉字文本编码GBK？该脚本编码utf8，win7运行OK，win10待测试
import shutil,os,sys,time,subprocess,win32con,win32api,re,psutil

# 公共变量处理
 #Catia路径设置：全局环境配置文件
timeWait=15
CATGlobalEnvPath="没有找到对应路径，请检查或者手动选择" #开发用测试路径
# CATGlobalEnvPath="D:\Program Files\Dassault Systemes\CATEnv" #但老师学生机器路径
# CATUserSettingPath=os.getcwd()+r"\CAT配置文件"
CATInstallPath="" 
CATEnvfName=""
CATUserSettingPath=""
projName="Catia__setting_tool"
proInfo=r"https://gitee.com/dvaloveu/catia_setting_tool"
contInfo="465318701 答案：没有 或者在项目仓库留言"
 #目标路径
# dest=os.getcwd()+r"\test"
 # 配置文件路径
dir_setting=os.getcwd()+r"\res\CATEnv2019"
 # 环境文件路径
# dir_env=os.getcwd()+r"\CATEnv"
 
#生成资源文件目录访问路径 开发时注释掉
def resource_path(relative_path):
    if getattr(sys, 'frozen', False): #是否Bundle Resource
        base_path = sys._MEIPASS
    else:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

dir_setting = resource_path(os.path.join("res","CATEnv2019"))
# print (dir_setting)
# print ("dir_setting== "+dir_setting)

def get_Reg_key(path,key_):
    reg_root = win32con.HKEY_LOCAL_MACHINE
    #reg_root = win32con.HKEY_CLASSES_ROOT
    reg_path = r'%s' % path
    reg_flags = win32con.KEY_READ | win32con.KEY_WOW64_64KEY
    # 读取键值
    key = win32api.RegOpenKey(reg_root, reg_path, 0, reg_flags)
    value, key_type = win32api.RegQueryValueEx(key, key_)
    
    #关闭键
    win32api.RegCloseKey(key)
    return {"value":value}

 #启动一次catia并且终止
def run_demo_exe(fpath):
    global timeWait
    myPopenObj = subprocess.Popen([fpath], shell=True)
    try:
        myPopenObj.wait(timeout=timeWait)
        # myPopenObj.wait()
        # if psutil.pid_exists(myPopenObj.pid) and psutil.pid_exists(myPopenObj.pid) in psutil.pids():
        #     print("程序运行")
    except Exception as e:
        print("===== process timeout ======")
        # myPopenObj.kill()
        myPopenObj.terminate()
        os.system("taskkill /im CNEXT.exe") 
        return None

def get_desk_p():
    return os.path.join(os.path.expanduser('~'),"Desktop")


 
def main():
#处理环境变量文件，增加快速启动环境配置
     #遍历全局环境变量文件夹，找到第一个txt文件，如果不止一个就报错,注意版本
    global CATGlobalEnvPath
    global CATInstallPath
    global CATEnvfName
    global CATUserSettingPath
    print("正在修改环境变量，增加快速启动配置")
    print(CATGlobalEnvPath)
    for root, dirs, files in os.walk(CATGlobalEnvPath, topdown=False):
                for name in files:
                    fPath=str(os.path.join(root, name))
                    
                    if name.__contains__(CATEnvfName+".txt"):
                        #创建txt环境文件备份
                        print("环境变量路径："+fPath)
                        print("正在备份当前环境变量文件。。")
                        shutil.make_archive(root+"备份"+str(time.time()),'zip',root_dir=root)
                        env_f=open(fPath,mode="a")                            
                        env_f.write('''CNEXTBACKGROUND=yes\n  
CATNoStartDocument=no\n
CNEXTSPLASHSCREEN=no\n  
CATLM_ODTS=1\n 
L_WILSON_LAN=1\n  
CGM_ROLLINGOFFSET=1\n  
TAILLE_MEMOIRE_CHOISIE=1 \n 
SHOW_CST_CHILDREN=1 \n 
MM_NO_REPLACE=1 \n 
IRD_PRODUCTTOPART=1 \n 
MFG_MULTI_MP_APPLY=1 \n 
MFG_CATMFG_REMOVE_MOTION_TOOL_CHANGE=1\n 
KEEP_HIDDEN_ELEMENT=1 \n 
cleanV4Topology=1 \n 
CATMigrSolidMUV4AsPart=1 \n 
REPORT_BREP_INFO=1 \n 
V5V4SaveAsVolume=1 \n 
V5V4CleanTolerance=0.01 \n 
V5V4MaxSimplif=1 \n ''')
                        env_f.close #写入结束
                        print("环境变量修改完毕")
                        
#将已有配置文件复制到Catia默认配置文件路径                        
    # 获取CATUserSettingPath路径
                        print("正在获取用户配置文件路径")
                        env_f=open(fPath)
                        for line in env_f:
                            # print(line)
                            if line.__contains__("CATUserSettingPath"): 
                                line = line.split("=")
                                # print(line)
                                if line[1].__contains__("CSIDL_APPDATA"):
                                    path=line[1].replace("CSIDL_APPDATA",os.getenv("APPDATA"))
                                    path=path.replace("\n","")
                                    print("用户配置文件存放路径为："+path) #打印CATUserSettingPath
                                    CATUserSettingPath=path  
                                else:
                                    path=path.replace("\n","")
                                    print("用户配置文件存放路径为："+path)
                                    CATUserSettingPath=path
                            #获取catia安装路径，准备启动catia                
                            if line.__contains__("CATInstallPath"): 
                                line = line.split("=")
                                # print(line)
                                CATInstallPath=line[1].replace("\n","")+r"\code\bin\CATSTART.exe"
                                
                                print("Catia启动文件路径为："+CATInstallPath) #打印CATUserSettingPath
   

   
    # print ("启动Catia，等待启动成功。。。")
    # run_demo_exe(CATInstallPath)
    # print ("终止Catia进程")

    #将已有配置文件复制到Catia默认配置文件路径
    print("正在备份当前配置文件")
    
    
    shutil.make_archive(CATUserSettingPath+"备份"+str(time.time()),'zip',root_dir=CATUserSettingPath+r'\\')
    print("导入覆盖当前配置文件")
    # shutil.copytree(dir_setting, CATUserSettingPath)
    print("资源文件路径："+dir_setting)
    if os.path.isdir(dir_setting)==False:
        print("资源路径不存在")
    shutil.copytree(dir_setting, CATUserSettingPath, dirs_exist_ok=True) #py38开始支持dir_exsit_OK参数
    shutil.unpack_archive(CATUserSettingPath+"\CATEnv2019.zip",CATUserSettingPath)
    # logpath=get_desk_p()+"\log"+time.strftime("%Y%m%d%H%M%S", time.localtime())+".txt"
    # print("日志路径:"+logpath)
    # with open(logpath,'a') as f:
    #     f.write("等待启动完毕时间："+str(timeWait)+"s")
    # print("修改用户配置完毕") 
    # print("执行完毕，请手动打开对应目录确认相关文件")
    # print("打开配置文件存放目录，请确认是否存在推荐配置文件说明文档")
    # os.startfile(CATUserSettingPath)
    # print("打开全局环境变量文件存放目录，请确认环境变量文件")
    # os.startfile(CATGlobalEnvPath)

########## main ##########################
#打印主显示：
print("================================") 
print('''配置文件归属：欧凡技术培训中心
用途：用于CATIA汽车设计教学使用
权限问题请联系微信：799735509''')
print("================================")
try:
    reg=get_Reg_key("SOFTWARE\Classes\CATIA.Part\shell\open\command","")
except Exception as e:  
    print("找不到注册表信息，请检查Catia是否安装正确")
    print(e)
else:
    # print(reg)
    # EnvPath=re.sub(r'(-env) (.*) (-direnv)', "", name)
    EnvfName=re.search(r'(-env) (.*) (-direnv)', str(reg))
    EnvPath=re.search(r'(-direnv) "(.*?)"', str(reg))
    # print(EnvfName)
    # print(EnvfName.groups())
    # print("全局环境变量文件名== "+EnvfName.groups()[1])
    # print("全局环境变量路径== "+EnvPath.groups()[1])
    CATGlobalEnvPath=EnvPath.groups()[1]
    CATEnvfName=EnvfName.groups()[1]
    print ("当前Catia全局环境储存目录为："+CATGlobalEnvPath)
    print("请确认与本机Catia环境编辑器中【全局环境】字段是否一致，如果有误请联系管理员")
    # print("源码&项目地址： https://gitee.com/dvaloveu/catia_setting_tool")
    print("测试平台:win7/win10 python版本：3.8.10 配置说明文档更新日期：2023.9.13 本工具更新日期：2023.9.15")
    print("-------------------------------------------------------------------------------------------------")
    main()
finally:
    # input("输入回车结束本程序")
    print('按任意键关闭')
    # time.sleep(5)
    os.system("pause")




# Reference：
# https://docs.python.org/3/library/shutil.html#directory-and-files-operations
# app = Application(backend="uia").start("D:\Program Files (x86)\CatiaV5-6R2020\win_b64\code\bin\CATSTART.exe")